package com.valuegroup.smarttodo.ui.todo.task;


import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.valuegroup.smarttodo.R;
import com.valuegroup.smarttodo.common.BaseRecyclerAdapter;
import com.valuegroup.smarttodo.common.BaseViewHolder;
import com.valuegroup.smarttodo.data.ServiceFactory;
import com.valuegroup.smarttodo.data.enums.TaskSortTypeEnum;
import com.valuegroup.smarttodo.data.model.AppStatus;
import com.valuegroup.smarttodo.data.vo.AppCustomCfg;
import com.valuegroup.smarttodo.data.vo.TaskItemVo;
import com.valuegroup.smarttodo.ui.search.SearchActivity;
import com.valuegroup.smarttodo.ui.todo.task.detail.TaskDetailActivity;
import com.valuegroup.smarttodo.ui.todo.task.qucikadd.QucikAddActivity;
import com.valuegroup.smarttodo.ui.todo.task.qucikadd.QucikAddInputCheckRule;
import com.valuegroup.smarttodo.ui.todo.task.qucikadd.QuickAddEditorCallback;
import com.valuegroup.smarttodo.ui.todo.task.qucikadd.QuickAddHolder;
import com.valuegroup.smarttodo.util.Cfg;

import net.cachapa.expandablelayout.ExpandableLayout;

import java.util.List;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.AppCompatCheckBox;
import androidx.appcompat.widget.PopupMenu;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * 待办>任务-首页
 */
public class TaskFragment extends Fragment {
    private static final String TAG = TaskFragment.class.getSimpleName();


    @BindView(R.id.labSort)
    TextView labSort;
    @BindView(R.id.btnAsc)
    ImageView btnAsc;
    @BindView(R.id.btnClose)
    ImageView btnClose;
    @BindView(R.id.expandableLayout)
    ExpandableLayout expandableLayout;
    @BindView(R.id.btnFastAdd)
    FloatingActionButton btnFastAdd;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;

    private Unbinder unbinder;
    private TaskAdapter adapter;
    private PopupMenu sortPopupMenu;
    private AppCustomCfg cfg;
    private boolean initFinish = false;

    public static TaskFragment newInstance() {
        return new TaskFragment();
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_task, container, false);
        unbinder = ButterKnife.bind(this, view);
        initFinish = true;

        cfg = Cfg.getCfg(getContext());

        // 初始化列表
        recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        //adapter = new OldTaskAdapter(view, spHideFinish, spSortType, spIsAsc);
        adapter = new TaskAdapter(view.getContext(), loadData(), multiTypeSupport);
        recyclerView.setAdapter(adapter);

        // item项左右滑动和上下拖动处理
        //ItemTouchHelper mItemTouchHelper = new ItemTouchHelper(new TaskTouchHelper(adapter, getActivity()));
        //mItemTouchHelper.attachToRecyclerView(recyclerView);

        // 排序菜单
        sortPopupMenu = new PopupMenu(view.getContext(), labSort);
        sortPopupMenu.inflate(R.menu.menu_task_sort);
        sortPopupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                TaskSortTypeEnum t = TaskSortTypeEnum.getSortTypeForMenuId(item.getItemId());
                labSort.setText(t.getTextId());

                // 保存当前配置
                cfg.setTaskSortType(t.getSortType());
                Cfg.saveCfg(getContext(), cfg);

                // 刷新列表数据
                refreshAllData();
                return false;
            }
        });


        // 初始化排序功能
        TaskSortTypeEnum t = TaskSortTypeEnum.getSortTypeEnum(cfg.getTaskSortType());
        labSort.setText(t.getTextId());

        btnAsc.setImageResource(cfg.isTaskSortDesc() ? R.drawable.ic_shrink_gray3 : R.drawable.ic_expand_gray3);

        if (TaskSortTypeEnum.isNormal(cfg.getTaskSortType())) {
            if (expandableLayout.isExpanded()) {
                expandableLayout.collapse();
            }
        } else {
            expandableLayout.expand();
        }

        setHasOptionsMenu(true);
        return view;
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        menu.clear();
        inflater.inflate(R.menu.menu_task, menu);
    }

    @Override
    public void onPrepareOptionsMenu(@NonNull Menu menu) {

        menu.findItem(R.id.m4).setTitle(!cfg.isTaskHideFinish() ? R.string.task_m3 : R.string.task_m3_o);
        menu.findItem(R.id.m5).setTitle(!cfg.isTaskHideTimeout() ? R.string.task_m5 : R.string.task_m5_o);

        super.onPrepareOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.m1:
                // 全局搜索
                item.setIntent(new Intent(getActivity(), SearchActivity.class));
                break;
            case R.id.m2:
                // 任务清单
                item.setIntent(new Intent(getActivity(), TaskOrderActivity.class));
                break;
            case R.id.m3:
                // 任务排序
                expandableLayout.expand();

                // 弹出时默认使用星标排序
                cfg.setTaskSortType(TaskSortTypeEnum.QUADRANT.getSortType());
                Cfg.saveCfg(getContext(), cfg);

                refreshAllData();
                break;
            case R.id.m4:
                // 隐藏已完成项
                cfg.setTaskHideFinish(!cfg.isTaskHideFinish());
                Cfg.saveCfg(getContext(), cfg);

                refreshAllData();
                break;
            case R.id.m5:
                // 隐藏超时标签
                cfg.setTaskHideTimeout(!cfg.isTaskHideTimeout());
                Cfg.saveCfg(getContext(), cfg);

                refreshAllData();
                break;
            default:
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    @OnClick({R.id.btnFastAdd, R.id.labSort, R.id.btnAsc, R.id.btnClose})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            // 快速新增按钮点击事件
            case R.id.btnFastAdd:

                /*初始化 浮动在键盘上的快捷输入框*/
                QucikAddActivity.openEditor(
                        getContext(),
                        new QuickAddEditorCallback() {
                            @Override
                            public void onCancel() {
                                btnFastAdd.show();
                            }

                            @Override
                            public void onSubmit(String content) {
                                if (TextUtils.isEmpty(content)) {
                                    return;
                                }

                                // 新增内容
                                TaskItemVo item = ServiceFactory.getInstance().getTaskService().addTaskForFast(content, 10);
                                adapter.addItem(item);

                                //平滑到新增项
                                recyclerView.smoothScrollToPosition(adapter.getDataSize());
                            }

                            @Override
                            public void onAttached(final ViewGroup rootView) {
                                // 表情(暂时弃用)
                                /*final View flFaces = rootView.findViewById(R.id.quickly_add_fl_faces);
                                rootView.findViewById(R.id.quickly_add_fl_faces).setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        if (flFaces.getVisibility() == View.VISIBLE) {
                                            flFaces.setVisibility(View.GONE);
                                        } else {
                                            flFaces.setVisibility(View.VISIBLE);
                                        }
                                    }
                                });*/
                            }
                        },
                        new QuickAddHolder(QuickAddHolder.QuickAddType.TASK),
                        new QucikAddInputCheckRule(120, 2));

                btnFastAdd.hide();

                break;
            case R.id.labSort:
                // 选择排序类型
                sortPopupMenu.show();
                break;
            case R.id.btnAsc:
                // 选择排序方式
                refreshAllData();

                cfg.setTaskSortDesc(!cfg.isTaskSortDesc());
                Cfg.saveCfg(getContext(), cfg);

                btnAsc.setImageResource(!cfg.isTaskSortDesc() ? R.drawable.ic_expand_gray3 : R.drawable.ic_shrink_gray3);
                break;
            case R.id.btnClose:
                // 关闭排序面板
                if (expandableLayout.isExpanded()) {
                    expandableLayout.collapse();

                    // 恢复默认排序
                    cfg.setTaskSortType(TaskSortTypeEnum.NORMAL.getSortType());
                    cfg.setTaskSortDesc(false);
                    Cfg.saveCfg(getContext(), cfg);

                    refreshAllData();
                }
                break;
        }
    }


    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        /*if (isVisibleToUser && initFinish) {
            refreshAllData();
        }*/
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        refreshData(data);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    /**
     * 更新列表中某条数据
     * 没有指定的刷新内容时，刷新整个列表
     *
     * @param intent
     */
    private void refreshData(Intent intent) {
        if (intent == null) {
            refreshAllData();
            return;
        }

        long id = intent.getLongExtra(TaskDetailActivity.PARAMS_KEY, 0);
        int position = intent.getIntExtra(TaskDetailActivity.PARAMS_POSITION, 0);

        if (id == 0) {
            refreshAllData();
            return;
        }

        // 刷新列表中当前操作记录
        TaskItemVo data = ServiceFactory.getInstance().getTaskService().getTaskItemVo(id);
        adapter.refreshData(position, data);

        // 平移到指定位置
        recyclerView.smoothScrollToPosition(position);
    }

    /**
     * 更新列表所有数据
     */
    private void refreshAllData() {
        // 刷新列表数据
        adapter.refreshListData(loadData());
        // 平移到相关位置
        recyclerView.smoothScrollToPosition(0);
    }

    /**
     * 读取所有数据
     */
    private List<TaskItemVo> loadData() {
        return ServiceFactory.getInstance().getTaskService().findTaskForHome(cfg.isTaskHideFinish(), TaskSortTypeEnum.getSortTypeEnum(cfg.getTaskSortType()), cfg.isTaskSortDesc());
    }


    class TaskAdapter extends BaseRecyclerAdapter<TaskItemVo> {

        public TaskAdapter(Context context, List<TaskItemVo> data, MultiTypeSupport multiType) {
            super(context, data, multiType);
        }

        @Override
        public void bindView(BaseViewHolder v, TaskItemVo data, int position) {
            TextView labTitle = v.getView(R.id.labTitle);

            // 完成状态控制
            AppCompatCheckBox chkFinish = v.getView(R.id.chkFinish);
            chkFinish.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                    // 保存数据
                    ServiceFactory.getInstance().getTaskService().doFinish(data.getId(), b);

                    // 删除线及字体颜色控制
                    if (b) {
                        labTitle.setTextColor(ContextCompat.getColor(getContext(), R.color.textHint));
                        labTitle.getPaint().setStrikeThruText(true);// setFlags(Paint.STRIKE_THRU_TEXT_FLAG | Paint.ANTI_ALIAS_FLAG);
                    } else {
                        labTitle.setTextColor(ContextCompat.getColor(getContext(), R.color.textDefault));
                        labTitle.getPaint().setStrikeThruText(false);// setFlags(0);
                    }
                }
            });

            // 详情页跳转
            v.getView(R.id.rootLayout).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent intent = new Intent(view.getContext(), TaskDetailActivity.class);
                    intent.putExtra(TaskDetailActivity.PARAMS_KEY, data.getId());
                    intent.putExtra(TaskDetailActivity.PARAMS_POSITION, position);
                    startActivityForResult(intent, 1001);
                }
            });

            //System.out.println("bindView:"+ JSON.toJSONString(data));

            // 初始化item页面数据

            v.setText(R.id.labTitle, data.getLabTitle());
            v.setText(R.id.labCount, data.getLabBranch());

            // 截止日期
            if (!cfg.isTaskHideTimeout() && data.isStale() && !TextUtils.isEmpty(data.getLabDate())) {
                //v.setText(R.id.labTimeout, data.getLabDate());
                v.setViewVisibility(R.id.labTimeout, true);

                //TextView lab = v.getView(R.id.labTimeout);
                //lab.setTextColor(ContextCompat.getColor(getContext(), R.color.colorWarn));
            } else {
                v.setViewVisibility(R.id.labTimeout, false);
            }
            //v.setText(R.id.labMinute, data.getLabMinute());

            //v.setViewVisibility(R.id.labMinute, false);
            //v.setViewVisibility(R.id.tagRepeat, false);

            //v.setViewVisibility(R.id.labCount, data.isShowBranch());
            //v.setViewVisibility(R.id.tagStart, data.isShowStar());
            //v.setViewVisibility(R.id.tagStudy, data.isShowStudy());

            //v.setViewVisibility(R.id.barStatus, (data.isShowStudy() || data.isShowBranch() || data.isShowStar() || !TextUtils.isEmpty(data.getLabDate())));

            // 优先级
            ImageView imgQuadrant = v.getView(R.id.tagQuadrant);
            imgQuadrant.setImageResource(AppStatus.QuadrantTagArr[data.getQuadrant()]);
            //imgQuadrant.setColorFilter(ContextCompat.getColor(getmContext(), AppStatus.QuadrantColorArr[data.getQuadrant()]));

            chkFinish.setChecked(data.isShowFinish());
        }
    }

    private BaseRecyclerAdapter.MultiTypeSupport multiTypeSupport = new BaseRecyclerAdapter.MultiTypeSupport<TaskItemVo>() {
        @Override
        public int getLayoutId(List<TaskItemVo> datas, int position) {
            if (position == 0) {
                return R.layout.item_default_header;
            } else if (position == (datas.size() + 1)) {
                return R.layout.item_default_bottom;
            } else {
                return R.layout.item_task;
            }
        }

        @Override
        public int getAppendHeadLayoutSize() {
            return 1;
        }

        @Override
        public int getAppendBottomLayoutSize() {
            return 1;
        }

        @Override
        public boolean isBodyLayout(int dataSize, int position) {
            if (position == 0 || position == (dataSize + 1)) {
                return false;
            } else {
                return true;
            }
        }
    };
}
